<template>
	<view :class="[BackGround]" :style="[{'font-weight':Style,'font-family':Font,height:100 + '%',minHeight:height + 'px'}]">
		<cu-custom bgColor="bg-gradual-blue" isBack="true">
			<view slot="backText">返回</view>
			<view slot="content">人员添加</view>
		</cu-custom>
		<view :class="['margin-xs radius shadow shadow-lg bg-white' ,BackGroundBox]" v-if="isShow">
			<form @submit="formSubmit" @reset="formReset">
				<view :style="{marginBottom:100 + 'rpx'}">
					<view class="cu-form-group">
						<view class="title">员工号</view>
						<input type="text" disabled value="系统自动生成" />
					</view>
					<view class="cu-form-group">
						<view class="title">姓名</view>
						<input placeholder="XXX" type="text" name="LUSERNAME" />
					</view>
					<view class="cu-form-group">
						<view class="title">年龄</view>
						<input placeholder="请输入年龄" type="number" name="LAGE" />
					</view>
					<view class="cu-form-group">
						<view class="title">性别</view>
						<picker @change="PickerChange1" name="LGENDER" :value="index1" :range="picker1" range-key="name">
							<view class="picker">
								{{picker1[index1].name}}
							</view>
						</picker>
					</view>
					<view class="cu-form-group">
						<view class="title">邮箱</view>
						<input placeholder="请输入邮箱" type="text" name="LEMAIL" />
					</view>
					<view class="cu-form-group">
						<view class="title">身份证号</view>
						<input placeholder="请输入身份证号" type="number" name="LIDCARD" />
					</view>
					<view class="cu-form-group">
						<view class="title">开户行</view>
						<input placeholder="请输入开户行" type="text" name="LBANK" />
					</view>
					<view class="cu-form-group">
						<view class="title">银行账号</view>
						<input placeholder="请输入银行账号" :adjust-position="false" type="number" name="LBANKCODE" />
					</view>
					<view class="cu-form-group">
						<view class="title">手机号</view>
						<input placeholder="请输入手机号" :adjust-position="false" type="number" name="LMOBILE" />
					</view>
					<view class="cu-form-group">
						<view class="title">职位</view>
						<input placeholder="请输入职位" :adjust-position="false" type="text" name="LDUTYID" />
					</view>
					<view class="cu-form-group">
						<view class="title">车间</view>
						<picker @change="PickerChange3" name="LPLANTINDEX" :value="index3" :range="picker3" range-key="LNAME">
							<view class="picker">
								{{picker3[index3].LNAME}}
							</view>
						</picker>
					</view>
					<view class="cu-form-group">
						<view class="title">班次</view>
						<picker @change="PickerChange2" name="LCLASSINDEX" :value="index2" :range="picker2" range-key="LNAME">
							<view class="picker">
								{{picker2[index2].LNAME}}
							</view>
						</picker>
					</view>
					<view class="cu-form-group">
						<view class="title">工序</view>
						<picker @change="PickerChange4" name="LPRCTYPE" :value="index4" :range="picker4" range-key="LNAME">
							<view class="picker">
								{{picker4[index4].LNAME}}
							</view>
						</picker>
					</view>
					<view class="cu-form-group">
						<view class="title">是否离职</view>
						<switch @change="SwitchA" name="LISDIMISSION" :class="switchA?'checked':''" :checked="switchA?true:false"></switch>
					</view>
					<view class="cu-form-group">
						<view class="title">上传头像</view>
						<view class="grid col-4 grid-square flex-sub" style="justify-content:flex-end">
							<view class="bg-img" v-for="(item,index) in imgList" :key="index" @tap="ViewImage" :data-url="imgList[index]">
								<image :src="imgList[index]" mode="aspectFill"></image>
								<view class="cu-tag bg-red" @tap.stop="DelImg" :data-index="index">
									<text class='cuIcon-close'></text>
								</view>
							</view>
							<view class="solids" @tap="ChooseImage" v-if="imgList.length<1">
								<text class='cuIcon-cameraadd'></text>
							</view>
						</view>
					</view>
				</view>
				<button-father :Position="'tb-fa-fixed'">
					<button class="cu-btn bg-blue-gradual  lg shadow tb-flex cu-btn-new" form-type="reset">重置</button>
					<button class="cu-btn bg-gradual-blue  lg shadow tb-flex cu-btn-new" form-type="submit">确认</button>
				</button-father>
			</form>
		</view>
	</view>
</template>

<script>
	import ButtonFather from "@/colorui/components/ButtonFather.vue";
	import {
		mapGetters
	} from "vuex";
	import {
		postinsert,
		postaddStaff
	} from '@/service/insert'
	import {
		getselectReferList
	} from "@/service/selectList"
	export default {
		data() {
			return {
				height: this.screenHeight,
				picker1: [{
						name: "男"
					},
					{
						name: "女"
					}
				],
				picker2: [],
				isShow: false,
				picker3: [],
				picker4: [],
				imgList: [],
				imagename: '',
				index1: 0,
				index2: 0,
				index3: 0,
				index4: 0,
				switchA: false,
			};
		},
		components: {
			ButtonFather
		},
		computed: {
			...mapGetters(["Style", 'Font', 'BackGround', 'BackGroundBox'])
		},
		async onLoad() {
			getselectReferList(1005, '表头', 'LPLANTINDEX', {}).then(res => {
				if (res.code != '') {
					this.picker3 = res.data
				} else {
					this.isShow = true
					console.log(this.isShow);
				}
			})
			getselectReferList(1005, '表头', 'LCLASSINDEX', {}).then(res => {
				if (res.code != '') {
					this.picker2 = res.data
					this.isShow = true
				} else {
					this.isShow = true
				}
			})
			getselectReferList(1005, '表头', 'LPRCTYPE', {}).then(res => {
				if (res.code != '') {
					this.picker4 = res.data
					this.isShow = true
				} else {
					this.isShow = true
				}
			})
		},
		beforeDestroy() {
			this.closeSocket();
		},
		methods: {
			// 关闭websocket【离开这个页面的时候执行关闭】
			closeSocket() {
				this.socketTask.close({
					success(res) {
						// this.is_open_socket = false;
						console.log("关闭成功", res)
					},
					fail(err) {
						console.log("关闭失败", err)
					}
				})
			},
			PickerChange1(e) {
				this.index1 = e.detail.value;
			},
			PickerChange2(e) {
				this.index2 = e.detail.value;
			},
			PickerChange3(e) {
				this.index3 = e.detail.value;
			},
			PickerChange4(e) {
				this.index4 = e.detail.value;
			},
			SwitchA(e) {
				this.switchA = e.detail.value
			},
			// ---------------------------上传图片===================================
			ViewImage(e) {
				uni.previewImage({
					urls: this.imgList,
					current: e.currentTarget.dataset.url
				});
			},
			ChooseImage() {
				uni.getStorageSync('IP')
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], //从相册选择
					success: (res) => {
						this.imgList = res.tempFilePaths
						uni.uploadFile({
							// url:'http://192.168.31.29:8080/upload',
							url: uni.getStorageSync('IP') + ':' + uni.getStorageSync('PORT') + '/api/upload',
							filePath: this.imgList[0],
							header: {
								'token': uni.getStorageSync('token')
							},
							name: 'file',
							success: (res) => {
								let data = JSON.parse(res.data)
								if(data.code == 1) {
									let myres = JSON.parse(res.data)
									this.imagename = myres.data
								} else {
									uni.showToast({
										title:'上传失败！',
										icon:'none'
									})
								}
								
							}
						})
					}
				});
			},
			DelImg(e) {
				uni.showModal({
					title: '提示',
					content: '确定要删除这张图片吗？',
					cancelText: '取消',
					confirmText: '确认',
					success: res => {
						if (res.confirm) {
							this.imgList.splice(e.currentTarget.dataset.index, 1)
						}
					}
				})
			},
			// -----------------------------------------------------------
			formSubmit(e) {
				console.log(e);
				for (var item in e.detail.value) {
					console.log(item);
				}
				e.detail.value['LPHOTO'] = this.imagename
				console.log(e.detail.value['LPHOTO']);
				e.detail.value['LGENDER'] = this.picker1[this.index1].name
				console.log(this.picker1[this.index1].name);
				e.detail.value['LUSERCODE'] = 'auto'
				e.detail.value['LCLASSINDEX'] = this.picker2[this.index2].LNAME
				e.detail.value['LPLANTINDEX'] = this.picker3[this.index3].LNAME
				e.detail.value['LPRCTYPE'] = this.picker4[this.index4].LNAME
				//定义表单规则
				var rule = [{
						name: "LUSERNAME",
						checkType: "notnull",
						errorMsg: "请输入姓名"
					},
					{
						name: "LMOBILE",
						checkType: "phoneno",
						errorMsg: "请输入正确手机号"
					},

				];
				//进行表单检查
				var formData = e.detail.value;
				var checkRes = this.$graceChecker.check(formData, rule);
				if (this.imagename == '') {
					uni.showToast({
						title: '请上传头像',
						icon: "none"
					});
				} else if (!checkRes) {
					uni.showToast({
						title: this.$graceChecker.error,
						icon: "none"
					});
				} else {
					let staff = e.detail.value
					let faceInfo = {
						"LSTATERUN": 0,
						"LFACE": this.imagename,
						"LUSERNAME": e.detail.value['LUSERNAME'],
						"LISUPDATE": true,
						"LISUSED": true,
						"LISDELETE": false
					}
					console.log(this.imgList[0]);
					postaddStaff(staff, faceInfo).then(res => {
						if (res.code == 1) {
							this.socketTask = uni.connectSocket({
								// 【非常重要】必须确保你的服务器是成功的,如果是手机测试千万别使用ws://127.0.0.1:9099【特别容易犯的错误】
								url: "ws://" + uni.getStorageSync('IP').split("//")[1] + ':8888/' +
									"/websocket/socketServer.do",
								success(data) {
									console.log("websocket连接成功");
								},
							});
							// 消息的发送和接收必须在正常连接打开中,才能发送或接收【否则会失败】
							// console.log( this.deliverplan[i].LMACHINENO);
							let data = {
								from: '224524254',
								to: 'V1',
								data: 'AC'
							}
							let data2 = {
								from: '224425421',
								to: 'V2',
								data: 'AC'
							}
							this.socketTask.onOpen((res) => {
								console.log("WebSocket连接正常打开中...！");
								// this.is_open_socket = true;
								// 注：只有连接正常打开中 ，才能正常成功发送消息
								// setInterval(()=> {
								this.socketTask.send({
									data: JSON.stringify(data),
									async success() {
										console.log("消息发送成功");
									},
								});
								this.socketTask.send({
									data: JSON.stringify(data2),
									async success() {
										console.log("消息发送成功");
									},
								});
								uni.showToast({
									title: '添加成功！',
									icon: 'none'
								})
								setTimeout(() => {
									uni.navigateBack({
										delta: 1
									})
								}, 800)
								// },100)
								// 注：只有连接正常打开中 ，才能正常收到消息
								this.socketTask.onMessage((res) => {

								});
							})
							// 这里仅是事件监听【如果socket关闭了会执行】
							this.socketTask.onClose(() => {
								console.log("已经被关闭了")
							});
						} else {
							uni.showToast({
								title: '添加失败！',
								icon: 'none'
							})
						}
					})
				}
			},
			formReset(e) {
				console.log(e);
			}
		}
	};
</script>

<style>
	page {
		background-color: whitesmoke;
	}
</style>
